﻿using Shake.Domain.Infrastructures;
using Shake.Framework.Infrastructure;
using Shake.Framework.Models;
using Shake.Framework.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Shake.Framework.Database
{
    public static class DatabaseExtension
    {
        public static IList<T> Query<T>(this T entity) where T : ShakeEntity
        {
            IRepository Repository = Shake.Framework.Setup.AutofacConfig.Resolve<IRepository>();
            return Repository.Query<T>();
        }

        public static PaginationContent Page<T>(this IOrderedEnumerable<T> express, PageArgument pageArg, bool getPageInfo = true)
        {
            var dataSource = express.Skip((pageArg.Page - 1) * pageArg.Pages).Take(pageArg.Pages).ToList();
            PaginationContent result = new PaginationContent
            {
                Pages = pageArg.Pages,
                Page = pageArg.Page,
                Datas = dataSource
            };
            if (getPageInfo)
            {
                result.Total = express.Count(); // 考虑部分业务只需要数据，不需要分页数据，节省统计的资源
            }
            return result;
        }

        public static PaginationContent Page<T>(this IOrderedQueryable<T> express, PageArgument pageArg, bool getPageInfo = true)
        {
            var dataSource = express.Skip((pageArg.Page - 1) * pageArg.Pages).Take(pageArg.Pages).ToList();
            PaginationContent result = new PaginationContent
            {
                Pages = pageArg.Pages,
                Page = pageArg.Page,
                Datas = dataSource
            };
            if (getPageInfo)
            {
                result.Total = express.Count(); // 考虑部分业务只需要数据，不需要分页数据，节省统计的资源
            }
            return result;
        }
    }
}
